import { setCollectionBug } from "@utils/bugCollection";
import { copyToText } from "@utils/copyToClipboard";
import { getDatesInRange, getDayOfWeek, getSpecialDayBaseToday, getTodayDate } from "@utils/getDate";
import { BugReportListItem, getReportBugsByDate } from "@utils/getReportBugs";

interface BugHistoryItem {
  date: string;
  bugId: string;
  bugName: string;
  bugUrl: string;
}

export const bugHistoryModal = () => {
  const div = document.createElement("div");
  div.id = "bug_history_vue_app";
  document.body.appendChild(div);

  const days = getDatesInRange(getSpecialDayBaseToday(1), 14);
  const bugHistory: BugHistoryItem[] = [];

  for (let i = 0; i < days.length; i++) {
    const date = days[i];
    const reportLocal = getReportBugsByDate(date);
    
    if(reportLocal.length > 0) {
      const ids: string[] = [];
      const bugItems = reportLocal as BugReportListItem[];
      
      for (let i = 0; i < bugItems.length; i++) {
        const bugItem = bugItems[i];

        if(ids.includes(bugItem.id)) {
          continue;
        }

        ids.push(bugItem.id);

        bugHistory.push({
          date,
          bugId: bugItem.id,
          bugName: bugItem.name,
          bugUrl: bugItem.url,
        })
      }
    }
  }

  const { createApp, ref, reactive, h } = Vue;

  const app = createApp({
    template: `
      <n-modal v-model:show="showModal" preset="dialog" style="width: 60vw; height: 60vh">
        <template #header>
          <div>历史记录</div>
        </template>
        <div>
          <n-flex vertical>
            <n-flex style="align-items: center;">
              <div style="width: 50px;">搜索：</div>
              <div style="400px;">
                <n-select
                  v-model:value="selectedValue"
                  filterable
                  :options="options"
                  @update:value="handleUpdateValue"
                ></n-select>
              </div>
              <n-button size="small" tertiary strong @click="copyToday">复制当天</n-button>
              <n-button size="small" tertiary strong @click="copyWeek">复制当周</n-button>
            </n-flex>
            <div>
              <n-data-table
                :columns="columns"
                :data="data"
                :bordered="true"
                max-height="calc(60vh - 170px)"
              />
            </div>
          </n-flex>
        </div>
      </n-modal>
    `,
    setup() {
      const showModal = ref(true);
      const selectedValue = ref("全部");
      const options = reactive(days.map((day) => {
        return {
          label: day + " " + getDayOfWeek('zhou', day),
          value: day,
        }
      }));
      options.unshift({
        label: "全部",
        value: "全部",
      });
      let data = ref<any[]>(bugHistory);
      const columns = ref<any[]>([
        {
          title: "日期",
          dataIndex: "date",
          key: "date",
          width: 120,
        },
        {
          title: "ID",
          dataIndex: "bugId",
          key: "bugId",
          width: 100,
        },
        {
          title: "名称",
          dataIndex: "bugName",
          key: "bugName",
          width: "calc(60vw - 610px)",
          ellipsis: {
            tooltip: true
          }
        },
        {
          title: "URL",
          dataIndex: "bugUrl",
          key: "bugUrl",
          width: 200,
          ellipsis: {
            tooltip: true
          }
        },
        {
          title: "操作",
          key: "actions",
          width: 180,
          render: (row: any) => {
            return h(
              naive.NSpace,
              {
                horizontal: true
              },
              {
                default: () => [
                  h(
                    naive.NButton,
                    {
                      strong: true,
                      tertiary: true,
                      size: "small",
                      textContent: "打开",
                      onClick: () => window.open(row.bugUrl, "_blank")
                    }
                  ),
                  h(
                    naive.NButton,
                    {
                      strong: true,
                      tertiary: true,
                      size: "small",
                      textContent: "收藏",
                      onClick: () => {
                        setCollectionBug(row.bugId, row.bugName, row.bugUrl);
                      }
                    }
                  )
                ]
              }
            );
          }
        }
      ]);

      const handleUpdateValue = (value: string) => {
        if (value === "全部") {
          data.value = bugHistory;
          return;
        }

        data.value = bugHistory.filter((item) => item.date === value);
      }

      const copyToday = () => {
        const today = getTodayDate();
        const todayData = bugHistory.filter((item) => item.date === today);
        const text = todayData.map((item, index) => (index + 1) + ". " + item.bugId + " " + item.bugName).join("\n");
        copyToText(text);
      }

      const copyWeek = () => {
        const week = getDatesInRange(getSpecialDayBaseToday(1), 7);
        const weekData = bugHistory.filter((item) => week.includes(item.date));
        const text = weekData.map((item, index) => (index + 1) + ". " + item.bugId + " " + item.bugName).join("\n");
        copyToText(text);
      }

      return {
        showModal,
        selectedValue,
        options,
        data,
        columns,
        handleUpdateValue,
        copyToday,
        copyWeek,
      }
    }
  });

  app.use(naive);
  app.mount("#bug_history_vue_app");
}

